<template>
  <vxe-modal
    ref="treeModal"
    v-model="visible"
    :width="1024"
    :height="600"
    title="树状视图"
    destroy-on-close
    show-footer
    @close="cancel"
  >
    <el-row style="margin-bottom: 12px;">
      <el-col :span="24">
        <el-button type="primary" icon="el-icon-circle-plus-outline" @click="addNew">添加子项</el-button>
        <el-button type="danger" icon="el-icon-close" @click="deleteClick">删除</el-button>
      </el-col>
    </el-row>
    <el-row class="content">
      <el-col :span="6">
        <el-tree
          :props="{
            children: 'childs',
            label: 'text',
          }"
          node-key="id"
          :expand-on-click-node="false"
          :highlight-current="true"
          ref="tree"
          @node-click="handleNodeClick"
          :load="loadNode"
          lazy
        />
      </el-col>
      <el-col :span="18" class="content-right-col">
        <el-form
          ref="validateForm"
          :model="models.model"
          label-width="120px"
          :rules="rules"
          style="padding: 12px 0;"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="名称：">
                <el-input v-model="models.model.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编码：">
                <el-input v-model="models.model.code"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="排序号：">
                <el-input v-model="models.model.sort"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否启用：">
                <el-radio v-model="models.model.isEnabled" :label="true">是</el-radio>
                <el-radio v-model="models.model.isEnabled" :label="false">否</el-radio>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="预留字段1：">
                <el-input v-model="models.model.reserved1"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预留字段2：">
                <el-input v-model="models.model.reserved2"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="预留字段3：">
                <el-input v-model="models.model.reserved3"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注：">
                <el-input type="textarea" v-model="models.model.memo"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
    </el-row>

    <template #footer>
      <el-row>
        <el-col :span="24">
          <el-button type="primary" @click="save">保存</el-button>
        </el-col>
      </el-row>
    </template>
  </vxe-modal>
</template>

<script>
import request from "@/utils/request";
import _ from "lodash";
export default {
  name: "get-tree",
  props: {
    value: Boolean,
    typeId: String,
  },
  data() {
    return {
      visible: false,
      models: {
        model: {},
      },
      blankModel: {},
      rules: {},
      pageAction: "create",
      primaryKey: {},
      urls: {},
    };
  },
  watch: {
    value(visible) {
      this.visible = visible;
    },
  },
  methods: {
    cancel() {
      this.$emit("cancel");
    },
    handleNodeClick(item, node, $node) {
      let id = item.id;
      if (id == "root") {
        this.addNew();
        return;
      } else if (id) {
        request({
          url: "/admin/sysDictItem/getItem",
          method: "get",
          params: { itemId: id },
        }).then((m) => {
          m = m || {};
          this.pageAction = "edit";
          this.primaryKey = { itemId: m.itemId };
          this.models.model = _.extend({}, this.models.model, m);
        });
      }
    },

    addNew() {
      this.pageAction = "create";
      this.primaryKey = {};
      this.$set(this.models, "model", Object.assign({}, this.blankModel));
    },

    deleteClick() {
      let $tree = this.$refs["tree"];
      let item = $tree.getCurrentNode();
      if (!item || !item.id) {
        this.msgError("请先选择要删除的字典明细");
        return;
      }
      let id = item.id;
      let params = { itemId: id };
      this.$confirm("确定删除嘛？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        request({
          url: this.urls.delete,
          method: "post",
          data: { delete: JSON.stringify([params]), ...this.models },
        }).then((rlt) => {
          if (rlt && rlt.success) {
            $tree.getNode(item).parent.loaded = false;
            $tree.getNode(item).parent.expand();
            this.msgSuccess("删除成功");
          } else {
            this.msgError(rlt.message || "删除失败");
          }
        });
      });
    },

    save() {
      let $tree = this.$refs["tree"];
      let item = $tree.getCurrentNode();
      if (!item || !item.id) {
        this.msgError("请选择父级节点");
        return;
      }
      let pm = _.extend({}, this.models, { pageAction: this.pageAction });
      if (this.pageAction == "create") {
        pm.model.typeId = this.typeId;
        pm.model.parentId = item.id == "root" ? "" : item.id;
      }
      request({
        url: this.urls.save,
        method: "post",
        data: { ...pm, ...this.primaryKey },
      }).then((rlt) => {
        if (rlt && rlt.success) {
          if (this.pageAction == "create") {
            $tree.getNode(item).loaded = false;
            $tree.getNode(item).expand();
          } else {
            $tree.getNode(item).parent.loaded = false;
            $tree.getNode(item).parent.expand();
          }
          this.msgSuccess("保存成功");
        } else {
          this.msgError(rlt.message || "保存失败");
        }
      });
    },

    loadNode(node, resolve) {
      let id = "#";
      if (node.data) {
        id = node.data.id;
      }
      // 异步加载子节点
      request({
        url: "/admin/sysDictItem/getChild",
        method: "get",
        params: { typeId: this.typeId, id: id },
      })
        .then((r) => {
          r.forEach((item) => {
            if (item.children) {
              item.childs = [];
            }
          });
          resolve(r);
        })
        .catch((e) => {
          this.msgError("获取数据失败，请稍后再试");
        });
    },
    getTreeModel() {
      request({
        url: "/admin/sysDictItem/getTreeModel",
        method: "get",
      }).then((vm) => {
        this.models = _.extend(vm.models);
        this.blankModel = _.extend(vm.models.model);
        this.urls = vm.urls || {};
      });
    },
  },
  created() {
    this.getTreeModel();
  },
};
</script>

<style scoped>
.content {
  border: 1px solid #ccc;
  border-left: none;
  border-right: none;
}
.content-right-col {
  border-left: 1px solid #ccc;
}
</style>